﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nuclex.UserInterface.Controls.Desktop;
using Nuclex.UserInterface.Controls;
using Microsoft.Xna.Framework.Graphics;
using Nuclex.UserInterface;
using System.IO;

namespace FierceWar
{
	public class LoadMapDialog : WindowControl
	{
		private LabelControl _message;
		private ListControl _list;
		private ButtonControl _load;
		private ButtonControl _cancel;

		public string[] FilePaths;
		public string MapName;

		public LoadMapDialog(GraphicsDevice graphicsDevice,
			List<EventHandler> eventHandlers)
		{
			EnableDragging = false;

			// Message.
			_message = new LabelControl("Which map do you want to edit ?");
			_message.Bounds = new Nuclex.UserInterface.UniRectangle(
				10.0f, 32.0f, 120.0f, 30.0f);

			// List.
			_list = new ListControl();
			_list.Bounds = new UniRectangle(10.0f, 60.0f, 480.0f, 230.0f);
			_list.Slider.Bounds.Location.X.Offset -= 1.0f;
			_list.Slider.Bounds.Location.Y.Offset += 1.0f;
			_list.Slider.Bounds.Size.Y.Offset -= 5.0f;
			_list.SelectionMode =
			  Nuclex.UserInterface.Controls.Desktop.ListSelectionMode.Single;
			_list.SelectionChanged += new EventHandler(SelectedChanged);

			// Load button.
			_load = new ButtonControl();
			_load.Text = "Load";
			_load.Bounds = new UniRectangle(
				new UniScalar(1.0f, -180.0f), new UniScalar(1.0f, -40.0f),
				80.0f, 25.0f
			);
			_load.Pressed += eventHandlers[0];

			// Cancel button.
			_cancel = new ButtonControl();
			_cancel.Text = "Cancel";
			_cancel.Bounds = new UniRectangle(
				new UniScalar(1.0f, -90.0f), new UniScalar(1.0f, -40.0f),
				80.0f, 25.0f
			);
			_cancel.Pressed += eventHandlers[1];

			// Dialog.
			float width = 500.0f;
			float height = 350.0f;
			Bounds = new Nuclex.UserInterface.UniRectangle(
				(graphicsDevice.Viewport.Width - width) / 2,
				(graphicsDevice.Viewport.Height - height) / 2,
				width, height);
			Title = "Load Map";
			Children.Add(_message);
			Children.Add(_list);
			Children.Add(_load);
			Children.Add(_cancel);
		}

		public void UpdateList()
		{
			_list.Items.Clear();
			_list.SelectedItems.Clear();

			System.IO.Directory.CreateDirectory("Map");
			FilePaths = Directory.GetFiles("Map/", "*.bsp");
			for (int i = 0; i < FilePaths.Length; i++)
			{
				_list.Items.Add(Path.GetFileNameWithoutExtension(FilePaths[i]));
			}

			_list.SelectedItems.Add(0);
		}

		private void SelectedChanged(object sender, EventArgs e)
		{
			if (_list.Items.Count > 0)
			{
				int[] tmp = _list.SelectedItems.ToArray();
				if (FilePaths.Length > 0)
				{
					MapName = Path.GetFileName(FilePaths[tmp[0]]);
					_load.Enabled = true;
				}
				else
				{
					_load.Enabled = false;
				} 
			}
		}
	}
}
